package com.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.service.LoginService;
import com.utils.Des;
import com.utils.ObjectUtils;
import com.utils.Ret;

@Controller
public class LoginController {

	private final Logger log = Logger.getLogger(LoginController.class); 
	@Autowired
	LoginService loginService;

	@RequestMapping(value = "/login.do")
	public void login(HttpServletRequest request,
			HttpServletResponse response,PrintWriter out) throws IOException {

		Ret ret = new Ret();
		Des des = new Des();
		try {
			String ocode = des.strDec(ObjectUtils.getStrVal(request.getParameter("ocode")),"key", null,null);//机构码
			String ucode = des.strDec(ObjectUtils.getStrVal(request.getParameter("ucode")) ,"key", null,null);// 用户名
			String pwd = des.strDec(ObjectUtils.getStrVal(request.getParameter("pwd")),"key", null,null);// 密码
			String p_code = request.getParameter("code");
			String code = des.strDec(ObjectUtils.getStrVal(p_code),"key", null,null);//验证码

			ret = loginService.doLogin(code, ucode, ocode, pwd, request);
			System.out.println(request.getSession().getAttribute("usertype"));
		} catch (Exception e) {
			e.printStackTrace();
			ret.setMessage("登录失败！");
			out.print(ret.toJsonString());
			out.flush();
			out.close();
		}
		
		out.print(ret.toJsonString());
		out.flush();
		out.close();
		
	}
	
	@RequestMapping(value = "/captcha.do")
	public void captcha(HttpServletRequest request, HttpServletResponse response) {

		// http://wenku.baidu.com/link?url=xmJi40TG4SfeP7ssB0repwKsqqgyzjQCuutwnJp1dC1TG_DHIif_BbNAirT3I9QP5P_YcPO8EMoNTypC56kabEisneJQUn1JS6SOqg-DdGi
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);

		com.utils.RandomValidateCode randomValidateCode = new com.utils.RandomValidateCode();

		try {
			randomValidateCode.getRandcode(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
